package com.mdd.admin.service.specification.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import com.google.common.collect.Lists;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.goods.IGoodsService;
import com.mdd.admin.service.specification.IGoodsSpecificationService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.goods.GoodsParam;
import com.mdd.admin.validate.specification.GoodsSpecificationParam;
import com.mdd.admin.vo.specification.GoodsSpecificationListVo;
import com.mdd.admin.vo.specification.GoodsSpecificationDetailVo;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.goods.GoodsSpecification;
import com.mdd.common.enums.GoodsCategoryStatusEnum;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.specification.GoodsSpecificationMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.StringUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 服务规格实现类
 */
@Service
public class GoodsSpecificationServiceImpl extends ServiceImpl<GoodsSpecificationMapper, GoodsSpecification> implements IGoodsSpecificationService {

    @Resource
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private IGoodsService iGoodsService;
    /**
     * 服务规格列表
     *
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<GoodsSpecificationListVo>
     */
    @Override
    public PageResult<GoodsSpecificationListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        QueryWrapper<GoodsSpecification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        goodsSpecificationMapper.setSearch(queryWrapper, params, new String[]{
            "=:goodsId@goods_id:long",
            "like:name:str",
            "=:price:str",
            "=:incrementPrice@increment_price:str",
            "=:createdBy@created_by:long",
            "=:updatedBy@updated_by:long",
            "=:remark:str",
        });

        IPage<GoodsSpecification> iPage = goodsSpecificationMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<GoodsSpecificationListVo> list = new LinkedList<>();
        for(GoodsSpecification item : iPage.getRecords()) {
            GoodsSpecificationListVo vo = new GoodsSpecificationListVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 服务规格详情
     *
     * @param id 主键参数
     * @return GoodsSpecification
     */
    @Override
    public GoodsSpecificationDetailVo detail(Integer id) {
        GoodsSpecification model = goodsSpecificationMapper.selectOne(
                new QueryWrapper<GoodsSpecification>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        GoodsSpecificationDetailVo vo = new GoodsSpecificationDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 服务规格新增
     *
     * @param goodsSpecificationParam 参数
     */
    @Override
    @Transactional
    public void add(GoodsSpecificationParam goodsSpecificationParam) {
        GoodsSpecification goodsSpecification = goodsSpecificationMapper.selectOne(
                new QueryWrapper<GoodsSpecification>()
                    .eq("goods_id", goodsSpecificationParam.getGoodsId()).last("LIMIT 1"));

        GoodsSpecification goodsSpecificationBean = goodsSpecificationMapper.selectOne(
                new QueryWrapper<GoodsSpecification>()
                        .eq("name", goodsSpecificationParam.getName())
                        .eq("goods_id", goodsSpecificationParam.getGoodsId())
                        .last("LIMIT 1"));
        if(!Objects.isNull(goodsSpecificationBean) && goodsSpecificationBean.getName() != null){
            throw new OperateException("该类型服务的规格名称已经被填写");
        }
        if (goodsSpecification!= null
                && goodsSpecification.getIncrementPrice()!= null
                && goodsSpecification.getPreferentialQuantity() != null
                && goodsSpecificationParam.getIncrementPrice() != null
                && goodsSpecificationParam.getPreferentialQuantity() != null){
            throw new OperateException("该服务只能被填写一次！!");
        }

        GoodsSpecification model = new GoodsSpecification();
        model.setGoodsId(goodsSpecificationParam.getGoodsId());
        model.setName(goodsSpecificationParam.getName());
        model.setPrice(goodsSpecificationParam.getPrice());
        model.setBuyNumber(goodsSpecificationParam.getBuyNumber());
        model.setIncrementPrice(goodsSpecificationParam.getIncrementPrice());
        model.setCreatedBy(new Long(LikeAdminThreadLocal.getAdminId()));
        model.setUpdatedBy(new Long(LikeAdminThreadLocal.getAdminId()));
        model.setPreferentialQuantity(goodsSpecificationParam.getPreferentialQuantity());
        model.setRemark(goodsSpecificationParam.getRemark());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setGoodsName(goodsSpecificationParam.getGoodsName());
        if(goodsSpecification!= null){
            String group = goodsSpecification.getSpecificationGroup();
            model.setSpecificationGroup(group);
        }
        else{
            model.setSpecificationGroup(UUID.randomUUID().toString());
        }
        goodsSpecificationMapper.insert(model);
    }

    /**
     * 服务规格编辑
     *
     * @param goodsSpecificationParam 参数
     */
    @Override
    @Transactional
    public void edit(GoodsSpecificationParam goodsSpecificationParam) {
        GoodsSpecification model = goodsSpecificationMapper.selectOne(
                new QueryWrapper<GoodsSpecification>()
                    .eq("id",  goodsSpecificationParam.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setGoodsId(goodsSpecificationParam.getGoodsId());
        model.setName(goodsSpecificationParam.getName());
        model.setPrice(goodsSpecificationParam.getPrice());
        model.setIncrementPrice(goodsSpecificationParam.getIncrementPrice());
        model.setUpdatedBy(new Long(LikeAdminThreadLocal.getAdminId()));
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setRemark(goodsSpecificationParam.getRemark());
        model.setGoodsName(goodsSpecificationParam.getGoodsName());
        model.setPreferentialQuantity(goodsSpecificationParam.getPreferentialQuantity());
        Goods id = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("id", model.getGoodsId()));
        id.setName(model.getGoodsName()+model.getName());
        id.setPrice(goodsSpecificationParam.getPrice());
        id.setStatus(GoodsCategoryStatusEnum.WAREHOUSE.getStatus());
        //goodsMapper.updateById(id);
        GoodsParam goodsParam = new GoodsParam();
        BeanUtils.copyProperties(id,goodsParam);
        iGoodsService.edit(goodsParam);
        //
        goodsSpecificationMapper.updateById(model);
    }

    /**
     * 服务规格删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Long id) {
        GoodsSpecification model = goodsSpecificationMapper.selectOne(
                new QueryWrapper<GoodsSpecification>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        Goods goods = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("id", model.getGoodsId()));
        goods.setIsDelete(1);
        goodsMapper.updateById(goods);

        model.setIsDelete(1);
        goodsSpecificationMapper.updateById(model);
    }

}
